﻿''''http://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.80).aspx


Imports System.Net.Sockets
Imports System.Text
Imports Chat.SharedLib

Module Module1
    Dim clientsList As New List(Of TcpClient)
    Dim WithEvents sckt As Net.Sockets.Socket

    Sub Main()
        Dim serverSocket As New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 8888)
        Dim cl As TcpClient
        Dim counter As Integer

        serverSocket.Start()
        counter = 0

        While (True)
            counter += 1
            cl = serverSocket.AcceptTcpClient()
            Console.WriteLine("a new client connected")
            Dim o As New StateObject

            o.workSocket = cl.Client

            cl.Client.BeginReceive(o.buffer, 0, StateObject.BufferSize, Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnDataRecieve), o)

            clientsList.Add(cl)

        End While

        'clientSocket.Close()
        serverSocket.Stop()
        Console.ReadLine()
    End Sub

    Public Sub OnDataRecieve(ByVal e As IAsyncResult)
        Try

            Dim state = DirectCast(e.AsyncState, StateObject)
            Console.WriteLine("accepting data called")

            Dim bytesToRead As Integer = state.workSocket.EndReceive(e)

            If bytesToRead > 0 Then

                ' There  might be more data, so store the data received so far.
                Dim messsageContent = (Encoding.ASCII.GetString(state.buffer, 0, bytesToRead))
                Dim o As New Message
                o.Content = messsageContent

                state.Messages.Add(o)

                Console.WriteLine(o.Content)

            End If

            state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf OnDataRecieve), state)

        Catch ex As Exception

        End Try
    End Sub

    Public Sub OnDisconnect(ByVal a)

    End Sub

    Private Sub Send(ByVal client As Socket, ByVal data As String)
        ' Convert the string data to byte data using ASCII encoding.
        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)

        ' Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client)
    End Sub 'Send


    Private Sub SendCallback(ByVal ar As IAsyncResult)
        ' Retrieve the socket from the state object.
        Dim client As Socket = CType(ar.AsyncState, Socket)

        ' Complete sending the data to the remote device.
        Dim bytesSent As Integer = client.EndSend(ar)
        Console.WriteLine("Sent {0} bytes to server.", bytesSent)

        ' Signal that all bytes have been sent.
        'sendDone.Set()
    End Sub 'SendCallback

End Module




Public Class Pipe

    Property Name As String

End Class